package controllers

import (
	"strconv"
	"time"

	"cashew.com/cashew_api/dtos"
	"cashew.com/cashew_api/services"
	"cashew.com/cashew_common/configs"
	"cashew.com/cashew_common/constants"
	"github.com/beego/beego/v2/core/logs"
)

type CocoAuthController struct {
	BaseController
}

// 刷新token
func (c *CocoAuthController) RefreshToken() {
	req := dtos.RefreshTokenParams{}
	err := dtos.Bind(&req, c.Ctx)

	if err != nil {
		c.Error("参数错误: ", err)
		c.Result(constants.ERR_PARAM, nil)
		return
	}

	userId := req.UserId
	token := req.Token

	logs.Debug("userId: ", userId, " token: ", token)

	res, err := services.CocoVerifyuser(req.UserIdStr, token)
	if err != nil {
		c.Error("coco token 验证失败:CocoVerifyuser(%s, %s): %v", req.UserIdStr, token, err)
		c.Result(constants.ERR_COCO_TOKEN_VERIFY_FAILED, nil)
		return
	}
	if res.Result != 0 {
		c.Error("coco token 验证失败:CocoVerifyuser(%s, %s): %v", req.UserIdStr, token, res.Msg)
		c.Result(constants.ERR_COCO_TOKEN_VERIFY_FAILED, nil)
		return
	}

	cacheKey := configs.FilterTokenCacheKey
	Redisserver.HSet(cacheKey, strconv.FormatInt(userId, 10), token)
	Redisserver.Expire(cacheKey, 7*24*time.Hour)

	c.Result(constants.SUCCESS, nil)
}
